package com.marketing.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 网关配置类
 * 
 * @author Marketing Team
 * @version 1.0.0
 * @since 2025-09-23
 */
@Configuration
public class GatewayConfig {

    private static final Logger log = LoggerFactory.getLogger(GatewayConfig.class);

    /**
     * 自定义路由配置
     * 注意：主要路由在application.yml中配置，这里只配置辅助路由
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        log.info("初始化辅助路由配置...");
        
        return builder.routes()
                // 健康检查路由
                .route("health-check", r -> r.path("/health")
                        .uri("forward:/actuator/health"))
                
                // 网关自身的监控路由
                .route("gateway-actuator", r -> r.path("/actuator/**")
                        .uri("forward:/actuator"))
                        
                .build();
    }

    /**
     * CORS跨域配置
     */
    @Bean
    public CorsWebFilter corsFilter() {
        log.info("初始化CORS跨域配置...");
        
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许的源
        config.addAllowedOriginPattern("*");
        
        // 允许的请求头
        config.addAllowedHeader("*");
        
        // 允许的请求方法
        config.addAllowedMethod("*");
        
        // 允许携带认证信息
        config.setAllowCredentials(true);
        
        // 预检请求的缓存时间（秒）
        config.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        
        return new CorsWebFilter(source);
    }
}